'''
Created on Sep 14, 2012

@author: Eason
'''

import os
from os.path import walk
import re
import sys



class CSearchTxt():
    
    def __init__(self, dir, ext, content):
        self._dir = dir
        self._content = content
        self._ext = ext
        self._error = ''
        self._matchedfiles = []
        self._matchedlines = []
        
    def get_file_list(self):

        file_list = []
        walk(self._dir, self.file_enum_proc, file_list)
        return file_list
    
    def file_enum_proc(self,arg,directory,files):
        
        for f in files:
            index = f.rfind('.')
            if index < 0:
                continue
            ext = f[index+1:]
            print ext
            if ext == self._ext:
                print f
                arg.append(f)
    
    def set_last_error(self, err):
        self._error = err
        
    def get_last_error(self):
        return self._error
                
    def search(self):
        
        #check
        if not os.path.isdir(self._dir):
            self.set_last_error('is not a path')
            return False
        
       
        #get files
        fl = self.get_file_list()
        
        for f in fl:
            path = '%s\\%s' % (self._dir, f)
            fp = open(path, 'r')
            ls = fp.readlines()
            pat = r'.*%s.*' % self._content
            for l in ls:
                if re.match(pat, l, re.IGNORECASE):
                    if path not in self._matchedfiles:
                        self._matchedfiles.append(path)
                    if l not in self._matchedlines:
                        self._matchedlines.append(l)
        print 'matched files:'
        for r in self._matchedfiles:
            print '%s' % r
        return True
    
    def get_matched_files(self):
        return self._matchedfiles
    
    def get_matched_lines(self):
        return self._matchedlines
    

def main():
    argc = len(sys.argv)
    if argc != 4:
        print 'usage: txtsearch dir ext content'
        return
    
    print sys.argv
    
    s = CSearchTxt(sys.argv[1],sys.argv[2],sys.argv[3])
    if s.search():
        # open matched files
        ret = s.get_matched_files()
        for r in ret:
            os.startfile(r)
        
        # sort and save matched lines
        lines = s.get_matched_lines()
        lines.sort(key=str.lower)
        f = open('%s\\result.txt' % sys.argv[1], 'w')
        f.writelines(lines)
        f.close()
        os.startfile('%s\\result.txt' % sys.argv[1])
    else:
        print s.get_last_error()
if __name__ == '__main__':
    main()